package com.ctrip.openapi.java.base;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import org.xml.sax.InputSource;

import com.ctrip.openapi.java.base.model.City;
import com.ctrip.openapi.java.base.model.Hotel;
import com.ctrip.openapi.java.base.model.HotelDesc;
import com.ctrip.openapi.java.base.model.Images;
import com.ctrip.openapi.java.base.model.PricePlan;
import com.ctrip.openapi.java.base.model.RelativePosition;
import com.ctrip.openapi.java.base.model.Room;
import com.ctrip.openapi.java.utils.ConfigData;
import com.ctrip.openapi.java.utils.SignatureUtils;


// Http������
public class HttpAccessAdapter {
	// Http����̬��Ϣ
	private static ArrayList<HttpRequestProperty> StaticHttpRequestProperty = LoadStaticHttpRequestProperties();

	// ����ָ��������ָ����URL��
	public static String SendRequestToUrl(String requestContent,
			String urlString, String paraName) {
		InputStream errorStream = null;
		HttpURLConnection httpCon = null;
		try {
			URL url = new URL(urlString);
			String content = XMLToString(requestContent);
			String soapMessage = AddSoapShell(content);
			httpCon = (HttpURLConnection) url.openConnection();
			httpCon.setRequestMethod("POST");
			httpCon.setDoOutput(true);
			httpCon.setDoInput(true);

			for (int i = 0; i < StaticHttpRequestProperty.size(); i++) {
				httpCon.setRequestProperty(StaticHttpRequestProperty.get(i)
						.getName(), StaticHttpRequestProperty.get(i).getValue());
			}

			httpCon.setRequestProperty("Content-Length",
					String.valueOf(soapMessage.length()));

			OutputStream outputStream = httpCon.getOutputStream();
			outputStream.write(soapMessage.getBytes("UTF-8"));
			outputStream.close();

			InputStream inputStream = httpCon.getInputStream();
			// String encoding = httpCon.getRequestProperty("Accept-Encoding");
			BufferedReader br = null;
			// httpCon.getResponseMessage();
			if (httpCon.getRequestProperty("Accept-Encoding") != null) {
				try {
					GZIPInputStream gzipStream = new GZIPInputStream(
							inputStream);
					br = new BufferedReader(new InputStreamReader(gzipStream,
							"UTF-8"));
				} catch (IOException e) {
					br = new BufferedReader(new InputStreamReader(inputStream,
							"UTF-8"));
				}
			} else {
				br = new BufferedReader(new InputStreamReader(inputStream,
						"UTF-8"));
			}
			StringBuffer result = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				result.append(line);
			}
			return StringToXML(RemoveSoapShell(result.toString()));

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			errorStream = httpCon.getErrorStream();
			if (errorStream != null) {
				String errorMessage = null;
				String line = null;
				BufferedReader br = new BufferedReader(new InputStreamReader(
						errorStream));
				try {
					while ((line = br.readLine()) != null) {
						errorMessage += line;
					}
					return errorMessage;
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
			try {
				errorStream.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (SdkSystemException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpCon != null) {
				httpCon.disconnect();
			}
		}

		return "";
	}

	// ��Soap�����ӵ���������
	public static String AddSoapShell(
	/* String parameterName, */String patameterValue) throws Exception {
		BufferedReader bufferedReader = null;
		try {
			InputStream in = HttpAccessAdapter.class
					.getResourceAsStream("/RequestSOAPTemplate.xml");
			bufferedReader = new BufferedReader(new InputStreamReader(in));
			String text = bufferedReader.readLine();
			StringBuilder soapShellStringBuilder = new StringBuilder();
			while (text != null) {
				soapShellStringBuilder.append(text);
				text = bufferedReader.readLine();
			}
			String result = soapShellStringBuilder.toString();
			return result.replaceAll("string", patameterValue);
		} catch (FileNotFoundException e) {
			throw new SdkSystemException("�޷��ҵ�����ģ���ļ�");
		} catch (IOException e) {
			throw new SdkSystemException("�޷���ȡ����ģ���ļ�");
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
				}
			}
		}
	}

	// ɾ��Soap�����Ϣ
	public static String RemoveSoapShell(String source) {
		String result = "";
		int indexElementBegin = source.indexOf("<RequestResult>");
		int indexElementEnd = source.indexOf("</RequestResult>");
		if (indexElementBegin > 0 && indexElementEnd > 0) {
			result = source.substring(
					indexElementBegin + "<RequestResult>".length(),
					indexElementEnd);
		}
		return result;
	}

	// ��xml�ĵ�ת��Ϊ�ɴ�����ַ�
	public static String XMLToString(String source) {
		String result = source.replaceAll("<", "&lt;");
		result = result.replaceAll(">", "&gt;");
		return result;
	}

	// �����ص��ַ�ת��Ϊ�ɷ����л�XML�ı�
	public static String StringToXML(String source) {
		String result = source.replaceAll("&lt;", "<");
		result = result.replaceAll("&gt;", ">");
		return result;
	}

	// ���ؾ�̬��Ϣ
	public static ArrayList<HttpRequestProperty> LoadStaticHttpRequestProperties() {
		ArrayList<HttpRequestProperty> staticHttpRequestProperty = new ArrayList<HttpRequestProperty>();
		staticHttpRequestProperty.add(new HttpRequestProperty("Host",
				"openapi.ctrip.com"));
		// "crmint.dev.sh.ctriptravel.com"));
		staticHttpRequestProperty.add(new HttpRequestProperty("Content-Type",
				"text/xml; charset=UTF-8"));
		staticHttpRequestProperty.add(new HttpRequestProperty("SOAPAction",
				"http://ctrip.com/Request"));
		staticHttpRequestProperty.add(new HttpRequestProperty(
				"Accept-Encoding", "gzip, deflate"));

		return staticHttpRequestProperty;
	}

	// ping
	/*
	private static String testPingXml() {
		// String request =
		// "<Request><Header AllianceID=\"1\" SID=\"1\" TimeStamp=\"1352265056449\" Signature=\"E7C13030A4763015A3F7BA5C32613FCF\" RequestType=\"OTA_Ping\" AsyncRequest=\"false\" Timeout=\"0\" MessagePriority=\"3\"/><HotelRequest><RequestBody xmlns:ns=\"http://www.opentravel.org/OTA/2003/05\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><ns:OTA_PingRQ><ns:EchoData>jͨ����</ns:EchoData></ns:OTA_PingRQ></RequestBody></HotelRequest></Request>";
		String request = createtestPingRequestXml();
		String url = "http://openapi.ctrip.com/Hotel/OTA_Ping.asmx?wsdl";
		// String url =
		// "http://crmint.dev.sh.ctriptravel.com/Hotel/OTA_Ping.asmx?wsdl";
		String paraName = "requestXML";

		System.out.println(request);
		HttpAccessAdapter httpAccessAdapter = new HttpAccessAdapter();
		String response = httpAccessAdapter.SendRequestToUrl(request, url,
				paraName);
		System.out.println(response);
		return response;
	}*/

	public static String getResponseFromCtrip(String interfaceType,String request) {
		String url = "http://openapi.ctrip.com/Hotel/"+interfaceType+".asmx?wsdl";
		String paraName = "requestXML";
      //  System.out.println(request);
		HttpAccessAdapter httpAccessAdapter = new HttpAccessAdapter();
		String response = httpAccessAdapter.SendRequestToUrl(request, url,
						paraName);
		//System.out.println(response);
		return response;
	}
	
	private static String createtestPingRequestXml() {
		StringBuilder sb = new StringBuilder();
		try {
			sb.append("<Request><Header AllianceID=\"");
			sb.append(ConfigData.AllianceId);
			sb.append("\" SID=\"");
			sb.append(ConfigData.SId);
			sb.append("\" TimeStamp=\"");
			long timestamp = SignatureUtils.GetTimeStamp();
			sb.append(timestamp);
			sb.append("\" Signature=\"");

			String signature = SignatureUtils.CalculationSignature(timestamp
					+ "", ConfigData.AllianceId, ConfigData.SecretKey,
					ConfigData.SId, ConfigData.OTA_PING);

			sb.append(signature);
			sb.append("\" RequestType=\"");
			sb.append(ConfigData.OTA_PING);
			sb.append("\" AsyncRequest=\"false\" Timeout=\"0\" MessagePriority=\"3\"/><HotelRequest><RequestBody xmlns:ns=\"http://www.opentravel.org/OTA/2003/05\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><ns:OTA_PingRQ><ns:EchoData>aaaa</ns:EchoData></ns:OTA_PingRQ></RequestBody></HotelRequest></Request>");
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
		return sb.toString();
	}

	// hotels
	private static List<City> Cities() {

		/*
		 * <CityDetails> <CityDetail> <CityCode>BJS</CityCode> <City>1</City>
		 * <CityName>北京</CityName> <CityEName>Beijing</CityEName>
		 * <Country>1</Country> <Province>1</Province>
		 * <Airport>NAY,PEK</Airport>
		 */
		List<City> cities = new ArrayList<City>();

		SAXBuilder builder = new SAXBuilder();
		try {
			Document doc = builder.build(new File(
					"D:\\mynew\\RIMS\\src\\国内城市.xml"));
			Element root = doc.getRootElement();

			XPath xpath = XPath.newInstance("/CityDetails/CityDetail");
			List list = xpath.selectNodes(root);

			Iterator iter = list.iterator();
			while (iter.hasNext()) {
				City city = new City();
				Element cityDetail = (Element) iter.next();
				List<Element> cd = cityDetail.getChildren();

				city.setCityCode(cd.get(0).getText());
				city.setCity(cd.get(1).getText());
				city.setCityName(cd.get(2).getText());
				city.setCityEName(cd.get(3).getText());
				city.setCountry(cd.get(4).getText());
				city.setProvince(cd.get(5).getText());
				city.setAirport(cd.get(6).getText());
				// System.out.println(city.getCityCode()+":"+city.getCity()+":"+city.getCityName()+":"+city.getCityEName()+":"+city.getCountry()+":"+city.getProvince()+":"+city.getAirport());
				cities.add(city);
			}

		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// System.out.println(cities.size());
		return cities;
	}

	
	//==================================================
	// ctripinterface --------------
	private static String createHotelRequestXml(String hotelCityCode) {
		StringBuilder sb = new StringBuilder();
		try {
			sb.append("<Request><Header AllianceID=\"");
			sb.append(ConfigData.AllianceId);
			sb.append("\" SID=\"");
			sb.append(ConfigData.SId);
			sb.append("\" TimeStamp=\"");
			long timestamp = SignatureUtils.GetTimeStamp();
			sb.append(timestamp);
			sb.append("\" Signature=\"");

			String signature = SignatureUtils.CalculationSignature(timestamp
					+ "", ConfigData.AllianceId, ConfigData.SecretKey,
					ConfigData.SId, ConfigData.OTA_HotelSearch);
			sb.append(signature);
			sb.append("\" RequestType=\"");
			sb.append(ConfigData.OTA_HotelSearch);
			sb.append("\" AsyncRequest=\"false\" Timeout=\"0\" MessagePriority=\"3\"/><HotelRequest>"
					+ "<RequestBody xmlns:ns=\"http://www.opentravel.org/OTA/2003/05\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
					+ "<ns:OTA_HotelSearchRQ Version=\"1.0\" PrimaryLangID=\"zh\" xsi:schemaLocation=\"http://www.opentravel.org/OTA/2003/05 OTA_HotelSearchRQ.xsd\" xmlns=\"http://www.opentravel.org/OTA/2003/05\">"
					+ "<ns:Criteria AvailableOnlyIndicator=\"true\">"
					+ "<ns:Criterion>"
					+ "<ns:HotelRef HotelCityCode=\""
					+ hotelCityCode
					+ "\"/> "
					+ "</ns:Criterion>"
					+ "</ns:Criteria>"
					+ "</ns:OTA_HotelSearchRQ>"
					+ "</RequestBody></HotelRequest></Request>");
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}

		return sb.toString();
	}

	/*
	private static String getFindHotels(String hotelCityCode) {
		// String request =
		// "<Request><Header AllianceID=\"1\" SID=\"1\" TimeStamp=\"1352265056449\" Signature=\"E7C13030A4763015A3F7BA5C32613FCF\" RequestType=\"OTA_Ping\" AsyncRequest=\"false\" Timeout=\"0\" MessagePriority=\"3\"/><HotelRequest><RequestBody xmlns:ns=\"http://www.opentravel.org/OTA/2003/05\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><ns:OTA_PingRQ><ns:EchoData>jͨ����</ns:EchoData></ns:OTA_PingRQ></RequestBody></HotelRequest></Request>";

		String request = createHotelRequestXml(hotelCityCode);
		String url = "http://openapi.ctrip.com/Hotel/OTA_HotelSearch.asmx?wsdl";
		String paraName = "requestXML";

		// System.out.println(request);
		HttpAccessAdapter httpAccessAdapter = new HttpAccessAdapter();
		String response = httpAccessAdapter.SendRequestToUrl(request, url,
				paraName);
		// System.out.println(response);
		return response;
	}
*/
	// parseresponse
	private static List<Hotel> findHotels(String hotelCityCode) {
		List<Hotel> hotels = new ArrayList<Hotel>();
		String response = HttpAccessAdapter.getResponseFromCtrip(ConfigData.OTA_HotelSearch,createHotelRequestXml(hotelCityCode));
		// 创建一个新的字符串
		StringReader read = new StringReader(response);
		// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
		InputSource source = new InputSource(read);

		SAXBuilder builder = new SAXBuilder();
		try {
			Document doc = builder.build(source);
			Element root = doc.getRootElement();
			XPath xpath1 = XPath.newInstance("/Response/Header");
			List list1 = xpath1.selectNodes(root);
			Element item1 = (Element) list1.get(0);
			System.out.println(item1.getAttributeValue("ResultCode"));
			if ("Fail".equals(item1.getAttributeValue("ResultCode"))) {
				System.out.println(item1.getAttributeValue("ResultMsg"));
			}

			XPath xpath = XPath.newInstance("/Response/HotelResponse/*/*/*");
			List list = xpath.selectNodes(root);

			Iterator iter = list.iterator();
			while (iter.hasNext()) {
				Element item = (Element) iter.next();
				if (item.getAttributeValue("HotelName") != null
						&& !"".equals(item.getAttributeValue("HotelName"))) {
					Hotel hotel = new Hotel();

					hotel.setHotelName(item.getAttributeValue("HotelName"));
					hotel.setHotelCityCode(item
							.getAttributeValue("HotelCityCode"));
					hotel.setHotelCode(item.getAttributeValue("HotelCode"));
					hotel.setAreaID(item.getAttributeValue("AreaID"));
					// System.out.println(item.getAttributeValue("HotelName")+item.getAttributeValue("HotelCityCode")+item.getAttributeValue("HotelCode")+item.getAttributeValue("AreaID"));//
					Element vendorMessages = (Element) item.getChildren()
							.get(0);
					Element vendorMessage = (Element) vendorMessages
							.getChildren().get(0);
					Element subSection = (Element) vendorMessage.getChildren()
							.get(0);
					Element paragraph = (Element) subSection.getChildren().get(
							0);
					Element text = (Element) paragraph.getChildren().get(0);
					hotel.setParagraph(text.getText());
					// System.out.println(text.getText());//pic
					Element pos = (Element) item.getChildren().get(1);

					// System.out.println(pos.getAttributeValue("Latitude")+"--------"+pos.getAttributeValue("Longitude"));
					hotel.setLatitude(pos.getAttributeValue("Latitude"));
					hotel.setLongitude(pos.getAttributeValue("Longitude"));

					Element address = (Element) item.getChildren().get(2);
					Element addressLine = (Element) address.getChildren()
							.get(0);// System.out.println(addressLine.getText());
					Element addressCityName = (Element) address.getChildren()
							.get(1);// System.out.println(addressCityName.getText());
					Element addressPostalCode = (Element) address.getChildren()
							.get(2);// System.out.println(addressPostalCode.getText());
					hotel.setAddressLine(addressLine.getText());
					hotel.setCityName(addressCityName.getText());
					hotel.setPostalCode(addressPostalCode.getText());

					Element hotelStarRate = (Element) item.getChildren().get(3);
					// System.out.println(hotelStarRate.getAttributeValue("Rating"));
					Element ctripStarRate = (Element) item.getChildren().get(4);
					// System.out.println(ctripStarRate.getAttributeValue("Rating"));
					Element ctripRecommendRate = (Element) item.getChildren()
							.get(5);
					// System.out.println(ctripRecommendRate.getAttributeValue("Rating"));
					Element ctripCommRate = (Element) item.getChildren().get(6);
					// System.out.println(ctripCommRate.getAttributeValue("Rating"));
					Element commSurroundingRate = (Element) item.getChildren()
							.get(7);
					// System.out.println(commSurroundingRate.getAttributeValue("Rating"));
					Element commFacilityRate = (Element) item.getChildren()
							.get(8);
					// System.out.println(commFacilityRate.getAttributeValue("Rating"));
					Element commCleanRate = (Element) item.getChildren().get(9);
					// System.out.println(commCleanRate.getAttributeValue("Rating"));
					Element commServiceRate = (Element) item.getChildren().get(
							10);
					// System.out.println(commServiceRate.getAttributeValue("Rating"));

					hotel.setHotelStarRate(hotelStarRate
							.getAttributeValue("Rating"));
					hotel.setCtripStarRate(ctripStarRate
							.getAttributeValue("Rating"));
					hotel.setCtripRecommendRate(ctripRecommendRate
							.getAttributeValue("Rating"));
					hotel.setCtripCommRate(ctripCommRate
							.getAttributeValue("Rating"));
					hotel.setCommCleanRate(commCleanRate
							.getAttributeValue("Rating"));
					hotel.setCommFacilityRate(commFacilityRate
							.getAttributeValue("Rating"));
					hotel.setCommServiceRate(commServiceRate
							.getAttributeValue("Rating"));
					hotel.setCommSurroundingRate(commSurroundingRate
							.getAttributeValue("Rating"));

					List<RelativePosition> rp = new ArrayList<RelativePosition>();
					List<Element> relations = (List<Element>) item
							.getChildren();
					for (int i = 11; i < relations.size(); i++) {
						if ("RelativePosition".equals(relations.get(i)
								.getName())) {
							RelativePosition relativePosition = new RelativePosition();
							relativePosition.setHotelCode(hotel.getHotelCode());
							relativePosition.setDestName(relations.get(i)
									.getAttributeValue("Name"));
							relativePosition.setUnitMeasure(relations.get(i)
									.getAttributeValue("UnitOfMeasureCode"));
							relativePosition.setDistance(relations.get(i)
									.getAttributeValue("Distance"));

							rp.add(relativePosition);
						}
					}

					hotel.setRelativePosition(rp);
					// relativePositions.add(relativePosition);
					hotels.add(hotel);
				}
			}

		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return hotels;
	}

	// jdbc save
	private static void sychronizeHotels(String hotelCode) throws SQLException {

		List<Hotel> hList = HttpAccessAdapter.findHotels(hotelCode);
		int temp = 0;
		Connection con = null;
		java.sql.PreparedStatement st = null;
		java.sql.PreparedStatement st1 = null;
		Map<String, String> paraMap = new HashMap<String, String>();
		// Integer id = (Integer)
		// this.getDao().getSqlMapClientTemplate().queryForObject("maxbshz",paraMap);
		// String errorrowarea="none";

		// Date dates=new Date();
		con = DBPool.getConnection();
		if (con != null)
			System.out.println("connection get....................ok");
		st = con.prepareStatement("insert into Hotel ( hotelCode,hotelName,hotelCityCode,"
				+ "areaID, paragraph,latitude,longitude,addressLine,cityName,postalCode,hotelStarRate,ctripRecommendRate,ctripStarRate,"
				+ "ctripCommRate,commSurroundingRate,commFacilityRate,commCleanRate,commServiceRate)"
				+ " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
		st1 = con
				.prepareStatement("insert into RelativePosition ( hotelCode,destName,unitMeasure,distance)"
						+ " values(?,?,?,?)");
		Long beginTime = System.currentTimeMillis();
		con.setAutoCommit(false);

		// String aa="";
		for (int row = 0; row < hList.size(); row++) {
			//System.out.println(hList.get(row).getHotelCode()+":"+hList.get(row).getHotelName());
			st.setString(1, hList.get(row).getHotelCode());
			st.setString(2, hList.get(row).getHotelName());// aa=aa+","+creator;
			st.setString(3, hList.get(row).getHotelCityCode());
			st.setString(4, hList.get(row).getAreaID());
			st.setString(5, hList.get(row).getParagraph());
			st.setString(6, hList.get(row).getLatitude());
			st.setString(7, hList.get(row).getLongitude());
			st.setString(8, hList.get(row).getAddressLine());
			st.setString(9, hList.get(row).getCityName());
			st.setString(10, hList.get(row).getPostalCode());
			st.setString(11, hList.get(row).getHotelStarRate());
			st.setString(12, hList.get(row).getCtripRecommendRate());
			st.setString(13, hList.get(row).getCtripStarRate());
			st.setString(14, hList.get(row).getCtripCommRate());
			st.setString(15, hList.get(row).getCommSurroundingRate());
			st.setString(16, hList.get(row).getCommFacilityRate());
			st.setString(17, hList.get(row).getCommCleanRate());
			st.setString(18, hList.get(row).getCommServiceRate());
			st.addBatch();
			for (int row1 = 0; row1 < hList.get(row).getRelativePosition()
					.size(); row1++) {
				st1.setString(1, hList.get(row).getRelativePosition().get(row1)
						.getHotelCode());
				st1.setString(2, hList.get(row).getRelativePosition().get(row1)
						.getDestName());
				st1.setString(3, hList.get(row).getRelativePosition().get(row1)
						.getUnitMeasure());
				st1.setString(4, hList.get(row).getRelativePosition().get(row1)
						.getDistance());
				st1.addBatch();
			}
			/*
			 * if(row%1000==0){ st.executeBatch();st.clearBatch(); temp=0; }
			 * else { temp=row; }
			 */

		}
		/*
		 * if(temp!=0) {
		 */
		st1.executeBatch();
		st1.clearBatch();
		st.executeBatch();
		st.clearBatch();
		// }
		// System.out.println(aa+","+datestring);
		con.commit();
		Long endTime = System.currentTimeMillis();
		System.out.println("pst+batch：" + (endTime - beginTime) / 1000 + "秒");
		st1.close();
		st.close();
		con.close();

	}

	public static void downloadAllHotelBasicInfo() throws SQLException,
			InterruptedException {
		List<City> cities = HttpAccessAdapter.Cities();

		int count = 0;
		for (int i = 0; i < cities.size(); i++) {
			if (new Integer(cities.get(i).getCity()).intValue() >= 903) {
				System.out.println(cities.get(i).getCityName() + "--"
						+ cities.get(i).getCity());
				HttpAccessAdapter.sychronizeHotels(cities.get(i).getCity());
				// count++;
				// if(count%2==0){
				Thread.sleep(2000);
				// count=0;
				// }
			}
		}
		System.out.println("downloadAllHotelBasicInfo success!!");
	}
    //===============================================================
	
	
	//==========================================================
	private static String createHotelDescriptionRequestXml(String hotelCode) {
		StringBuilder sb = new StringBuilder();
		try {
			sb.append("<Request><Header AllianceID=\"");
			sb.append(ConfigData.AllianceId);
			sb.append("\" SID=\"");
			sb.append(ConfigData.SId);
			sb.append("\" TimeStamp=\"");
			long timestamp = SignatureUtils.GetTimeStamp();
			sb.append(timestamp);
			sb.append("\" Signature=\"");

			String signature = SignatureUtils.CalculationSignature(timestamp
					+ "", ConfigData.AllianceId, ConfigData.SecretKey,
					ConfigData.SId, ConfigData.OTA_HotelDescriptiveInfo);
			sb.append(signature);
			sb.append("\" RequestType=\"");
			sb.append(ConfigData.OTA_HotelDescriptiveInfo);
			sb.append("\" /><HotelRequest>"
					+ "<RequestBody xmlns:ns=\"http://www.opentravel.org/OTA/2003/05\" "
					+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
					+ "<OTA_HotelDescriptiveInfoRQ  Version=\"1.0\" "
					+ "xsi:schemaLocation=\"http://www.opentravel.org/OTA/2003/05 OTA_HotelDescriptiveInfoRQ.xsd\" "
					+ "xmlns=\"http://www.opentravel.org/OTA/2003/05\" "
					+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
					+ "<HotelDescriptiveInfos>"
					+ "<HotelDescriptiveInfo HotelCode=\""
					+ hotelCode
					+ "\">"
					+ "<HotelInfo SendData=\"true\"/>"
					+ "<FacilityInfo SendGuestRooms=\"true\"/>"
					+ "<AreaInfo SendAttractions=\"true\" SendRecreations=\"true\"/>"
					+ "<ContactInfo SendData=\"true\"/>"
					+ "<MultimediaObjects SendData=\"true\"/>"
					+ "</HotelDescriptiveInfo>" + "</HotelDescriptiveInfos>"
					+ "</OTA_HotelDescriptiveInfoRQ>"
					+ "</RequestBody></HotelRequest></Request>");
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}

		return sb.toString();
	}

	/*private static String getFindHotelDescription(String hotelCode) {
		String request = getResponseFromCtrip(ConfigData.OTA_HotelDescriptiveInfo,createHotelDescriptionRequestXml(hotelCode));
		String url = "http://openapi.ctrip.com/Hotel/OTA_HotelDescriptiveInfo.asmx?wsdl";
		String paraName = "requestXML";
		HttpAccessAdapter httpAccessAdapter = new HttpAccessAdapter();
		String response = httpAccessAdapter.SendRequestToUrl(request, url,
				paraName);
		return response;
	}*/

	private static List<HotelDesc> findHotelDescs(String hotelCode){
		List<HotelDesc> hoteldescs=new ArrayList<HotelDesc>();
			String response=HttpAccessAdapter.getResponseFromCtrip(ConfigData.OTA_HotelDescriptiveInfo,createHotelDescriptionRequestXml(hotelCode));
			
	        StringReader read = new StringReader(response);
	        InputSource source = new InputSource(read);
	      
	        SAXBuilder builder = new SAXBuilder();
	        try {      
	        	 Document doc = builder.build(source);  
	        	 Element root = doc.getRootElement();
	        	 XPath xpath1 = XPath.newInstance("/Response/Header");
	        	 List list1 =xpath1.selectNodes(root);
	        	 Element item1 = (Element)list1.get(0);
	        	 System.out.println(item1.getAttributeValue("ResultCode"));
	        	    if("Fail".equals(item1.getAttributeValue("ResultCode"))){
	        		 System.out.println(item1.getAttributeValue("ResultMsg"));
	        	    }
	        	 
	        	 XPath xpath = XPath.newInstance("/Response/HotelResponse/*/*/*");
	             List list = xpath.selectNodes(root);
                 //Iterator iter = list.iterator();
	             //while (iter.hasNext()){
	             for(int i=0;i<list.size();i++){
	            	 HotelDesc hotelDesc=new HotelDesc();
	            	 Element hotelDescriptiveContent = (Element)list.get(i);
	            	 hotelDesc.setBrandCode(hotelDescriptiveContent.getAttributeValue("BrandCode"));
	            	 hotelDesc.setHotelCode(hotelDescriptiveContent.getAttributeValue("HotelCode"));
	            	 Element wb = (Element)hotelDescriptiveContent.getChildren().get(0);
	            	 hotelDesc.setBuild(wb.getAttributeValue("WhenBuilt")==null?"":wb.getAttributeValue("WhenBuilt"));
	            	 
	            	 XPath hotelDescriptiveInfoRS = XPath.newInstance("//ns:OTA_HotelDescriptiveInfoRS");
	            	 hotelDescriptiveInfoRS.addNamespace("ns", "http://www.opentravel.org/OTA/2003/05");
	            	 Element hdirs=(Element)hotelDescriptiveInfoRS.selectSingleNode(root);
	            	 
	            	 XPath segmentCategory = XPath.newInstance("//ns:SegmentCategory");
	            	 segmentCategory.addNamespace("ns", "http://www.opentravel.org/OTA/2003/05");
	            	 Element seg=(Element)segmentCategory.selectSingleNode(root);
	            	 if(seg!=null){
	            	 hotelDesc.setSegCategpry(seg.getAttributeValue("Code"));
	            	 }
	            	 else{
	            		 hotelDesc.setSegCategpry("");
	            	 }
	            	 XPath descriptiveText = XPath.newInstance("//ns:Service");
	            	 descriptiveText.addNamespace("ns", "http://www.opentravel.org/OTA/2003/05");
	            	 List<Element> desc=(List<Element>)descriptiveText.selectNodes(root);
	            	 
	            	 for(int j=0;j<desc.size();j++){
	            		 Element child=(Element)desc.get(j).getChildren().get(0);
	            		// System.out.println(desc.get(j).getAttributeValue("Code")+"--"+desc.get(j).getAttributeValue("ID")+"--"+child.getText());
	            		 if("1001".equals(desc.get(j).getAttributeValue("ID"))){
	            			 hotelDesc.setService1001((hotelDesc.getService1001()==null?"":(hotelDesc.getService1001()+"@"))+child.getText());
	            		 }else if("1002".equals(desc.get(j).getAttributeValue("ID"))){
	            			 hotelDesc.setService1002((hotelDesc.getService1002()==null?"":(hotelDesc.getService1002()+"@"))+child.getText());
	            		 }else if("1003".equals(desc.get(j).getAttributeValue("ID"))){
	            			 hotelDesc.setService1003((hotelDesc.getService1003()==null?"":(hotelDesc.getService1003()+"@"))+child.getText());
	            		 }else if("1004".equals(desc.get(j).getAttributeValue("ID"))){
	            			 hotelDesc.setService1004((hotelDesc.getService1004()==null?"":(hotelDesc.getService1004()+"@"))+child.getText());
	            		 }
	            	 }
	            	 
	            	 XPath guestRoom = XPath.newInstance("//ns:GuestRoom");
	            	 guestRoom.addNamespace("ns", "http://www.opentravel.org/OTA/2003/05");
	            	 List<Element> guestRooms=(List<Element>)guestRoom.selectNodes(root);
	            	 List<Room> roomlist=new ArrayList();
	            	 for(int k=0;k<guestRooms.size();k++){
	            		 Room room=new Room();
	            		 room.setRoomTypeName(guestRooms.get(k).getAttributeValue("RoomTypeName"));
	            		 
	            		 List<Element> children=guestRooms.get(k).getChildren();
	            		 room.setStandardOccupancy(children.get(0).getAttributeValue("StandardOccupancy"));
	            		 room.setSize(children.get(0).getAttributeValue("Size"));
	            		 room.setRoomTypeCode(children.get(0).getAttributeValue("RoomTypeCode"));
	            		 room.setFloor(children.get(0).getAttributeValue("Floor"));
	            		 room.setBedTypeCode(children.get(0).getAttributeValue("BedTypeCode"));
	            		 room.setQuantity(children.get(0).getAttributeValue("Quantity"));
	            		 
	            		 Element amenities=(Element)guestRooms.get(k).getChildren().get(1);
	            		 List<Element> amenity=amenities.getChildren();
	            		 for(int q=0;q<amenity.size();q++){
	            			 List<Element> cd=amenity.get(q).getChildren();
	            			
	            			 room.setAmenity((room.getAmenity()==null?"":(room.getAmenity()+"@"))+cd.get(0).getText());
	            		 }
	            		 room.setHotelCode(hotelCode);
	            		 roomlist.add(room);
	            		 
	            	 }
	            	 hotelDesc.setRooms(roomlist);
	            	 
	            	 XPath imageItem = XPath.newInstance("//ns:ImageItem");
	            	 imageItem.addNamespace("ns", "http://www.opentravel.org/OTA/2003/05");
	            	 List<Element> imageItems=(List<Element>)imageItem.selectNodes(root);
	            	 List<Images> imageList=new ArrayList();
	            	 
	            	 for(int im=0;im<imageItems.size();im++){
	            		 Images image=new Images();
	            		 image.setCategory(imageItems.get(im).getAttributeValue("Category"));
	            		 Element url=(Element)((Element)imageItems.get(im).getChildren().get(0)).getChildren().get(0);
	            		 image.setUrl(url.getText());
	            		 image.setHotelCode(hotelCode);
	            		 image.setCaption(((Element)imageItems.get(im).getChildren().get(1)).getAttributeValue("Caption"));
	            		 imageList.add(image);
	            	 }
	            	 hotelDesc.setImages(imageList);
	            	 
	            	 XPath description = XPath.newInstance("//ns:Description");
	            	 description.addNamespace("ns", "http://www.opentravel.org/OTA/2003/05");
	            	 List<Element> descriptions=(List<Element>)description.selectNodes(root);
	            	 for(int im=0;im<descriptions.size();im++){
	            		 if("5".equals(descriptions.get(im).getParentElement().getAttributeValue("Category"))){
	            			 hotelDesc.setDetailDesc(descriptions.get(im).getText());
	            		 }else if("11".equals(descriptions.get(im).getParentElement().getAttributeValue("Category"))){
	            			 hotelDesc.setDesc(descriptions.get(im).getText());
	            		 }
	            	 }
	            	 
	            	 /*System.out.println(hotelDesc.getBrandCode()+":"+hotelDesc.getHotelCode()
	            			 +":"+hotelDesc.getBuild()+":"+hotelDesc.getSegCategpry()+
	            			 ":"+hotelDesc.getRooms().get(1).getRoomTypeName()+
	            			 ":"+hotelDesc.getRooms().get(1).getAmenity()+
	            			 ":"+hotelDesc.getImages().get(0).getCaption()+
	            			 ":"+hotelDesc.getImages().get(0).getUrl()+":"+hotelDesc.getDetailDesc()+"-->"+hotelDesc.getDesc());*/
	            	 hoteldescs.add(hotelDesc);
	             }
	        }catch (JDOMException e) {    
        		e.printStackTrace(); 
        		} catch (IOException e) {  
        			e.printStackTrace(); 
        			}
        return hoteldescs;
	}

	private static void sychronizeHotelDescs(String hotelCode,Connection con) throws SQLException {
System.out.println(hotelCode);
			List<HotelDesc> hList = HttpAccessAdapter.findHotelDescs(hotelCode);
			int temp = 0;
			//Connection con = null;
			java.sql.PreparedStatement st = null;
			java.sql.PreparedStatement st1 = null;
			java.sql.PreparedStatement st2 = null;
			Map<String, String> paraMap = new HashMap<String, String>();
			//con = DBPool.getConnection();
			if (con != null)
				System.out.println("connection get....................ok");
			st = con.prepareStatement("insert into hoteldesc(hotelCode,brandCode,build,segcategoty,sdesc,detailDesc,service1001,service1002,service1003,service1004)"
					+ " values(?,?,?,?,?,?,?,?,?,?)");
			st1 = con
					.prepareStatement("insert into hotelroom (roomTypeName,standardOccupancy,size,roomTypeCode,floor,bedTypeCode,quantity,amenity,hotelCode)"
							+ " values(?,?,?,?,?,?,?,?,?)");
			st2 = con
					.prepareStatement("insert into images (hotelCode,category,url,caption)"
							+ " values(?,?,?,?)");
			
			Long beginTime = System.currentTimeMillis();
			con.setAutoCommit(false);

			for (int row = 0; row < hList.size(); row++) {
				st.setString(1, hList.get(row).getHotelCode());
				st.setString(2, hList.get(row).getBrandCode());// aa=aa+","+creator;
				st.setString(3, hList.get(row).getBuild()==null?"":hList.get(row).getBuild());
				st.setString(4, hList.get(row).getSegCategpry()==null?"":hList.get(row).getSegCategpry());
				st.setString(5, hList.get(row).getDesc()==null?"":hList.get(row).getDesc());
				st.setString(6, hList.get(row).getDetailDesc()==null?"":hList.get(row).getDetailDesc());
				st.setString(7, hList.get(row).getService1001()==null?"":hList.get(row).getService1001());
				st.setString(8, hList.get(row).getService1002()==null?"":hList.get(row).getService1002());
				st.setString(9, hList.get(row).getService1003()==null?"":hList.get(row).getService1003());
				st.setString(10,hList.get(row).getService1004()==null?"":hList.get(row).getService1004());
	System.out.println("hotelCode:"+hList.get(row).getHotelCode()+"  brandcode:"+hList.get(row).getBrandCode()+"  seg:"+hList.get(row).getSegCategpry()
			+"  desc:"+hList.get(row).getDesc()+"  detail:"+hList.get(row).getDetailDesc()+"  1001:"+hList.get(row).getService1001()
			+"  1002:"+hList.get(row).getService1002()+"  1003:"+hList.get(row).getService1003()+"  1004:"+hList.get(row).getService1004());	
		
				st.addBatch();
				
				//roomTypeName,standardOccupancy,size,roomTypeCode,floor,bedTypeCode,quantity,amenity,hotelCode
				for (int row1 = 0; row1 < hList.get(row).getRooms()
						.size(); row1++) {
					st1.setString(1, hList.get(row).getRooms().get(row1).getRoomTypeName());
					st1.setString(2, hList.get(row).getRooms().get(row1).getStandardOccupancy()==null?"":hList.get(row).getRooms().get(row1).getStandardOccupancy()
							);
					st1.setString(3, hList.get(row).getRooms().get(row1).getSize()==null?"":hList.get(row).getRooms().get(row1).getSize()
							);
					st1.setString(4, hList.get(row).getRooms().get(row1).getRoomTypeCode()
							);
					//System.out.println(hList.get(row).getRooms().get(row1).getRoomTypeName()+"==="+hList.get(row).getRooms().get(row1).getFloor()+"==="+hList.get(row).getRooms().get(row1).getHotelCode());
					st1.setString(5, hList.get(row).getRooms().get(row1).getFloor()==null?"999":hList.get(row).getRooms().get(row1).getFloor()
							);
					st1.setString(6, hList.get(row).getRooms().get(row1).getBedTypeCode()==null?"":hList.get(row).getRooms().get(row1).getBedTypeCode()
							);
					st1.setString(7, hList.get(row).getRooms().get(row1).getQuantity()==null?"":hList.get(row).getRooms().get(row1).getQuantity()
							);
					st1.setString(8, hList.get(row).getRooms().get(row1).getAmenity()==null?"":hList.get(row).getRooms().get(row1).getAmenity()
							);
					st1.setString(9, hList.get(row).getRooms().get(row1).getHotelCode()
							);
					st1.addBatch();
					
				}
				for (int row2 = 0; row2 < hList.get(row).getImages()
						.size(); row2++) {
					//hotelCode,category,url,caption
					st2.setString(1, hList.get(row).getImages().get(row2).getHotelCode());
					st2.setString(2, hList.get(row).getImages().get(row2).getCategory()
							);
					st2.setString(3, hList.get(row).getImages().get(row2).getUrl()
							);
					st2.setString(4, hList.get(row).getImages().get(row2).getCaption()
							);
					st2.addBatch();
				}
				/*
				 * if(row%1000==0){ st.executeBatch();st.clearBatch(); temp=0; }
				 * else { temp=row; }
				 */

			}
			/*
			 * if(temp!=0) {
			 */
			st2.executeBatch();
			st2.clearBatch();
			st1.executeBatch();
			st1.clearBatch();
			st.executeBatch();
			st.clearBatch();
			// }
			// System.out.println(aa+","+datestring);
			con.commit();
			Long endTime = System.currentTimeMillis();
			System.out.println("pst+batch：" + (endTime - beginTime) / 1000 + "秒");
			st2.close();
			st1.close();
			st.close();
			//con.close();

		}
	
	/*
	public static void downloadAllHotelDesc() throws SQLException,
	InterruptedException {
          List<Hotel> hotels = new ArrayList();//HttpAccessAdapter.Cities();
          int count = 0;
            for (int i = 0; i < hotels.size(); i++) {
	          if (new Integer(hotels.get(i).getHotelCode()).intValue() >= 1) {
	              	System.out.println(hotels.get(i).getHotelCode() + "--"
			          	+ hotels.get(i).getHotelName());
		            HttpAccessAdapter.sychronizeHotelDescs(hotels.get(i).getHotelCode());
		         Thread.sleep(2000);
	          }
         }
            System.out.println("downloadAllHotelDesc success!!");
     }*/
	//=====================================================================
	
	
	private static String createPjRequestXml(String hotelCode) {
		StringBuilder sb = new StringBuilder();
		try {
			sb.append("<Request><Header AllianceID=\"");
			sb.append(ConfigData.AllianceId);
			sb.append("\" SID=\"");
			sb.append(ConfigData.SId);
			sb.append("\" TimeStamp=\"");
			long timestamp = SignatureUtils.GetTimeStamp();
			sb.append(timestamp);
			sb.append("\" Signature=\"");

			String signature = SignatureUtils.CalculationSignature(timestamp
					+ "", ConfigData.AllianceId, ConfigData.SecretKey,
					ConfigData.SId, ConfigData.D_HotelCommentList);
			sb.append(signature);
			sb.append("\" RequestType=\"");
			sb.append(ConfigData.D_HotelCommentList);
			sb.append("\" /><DomesticHotelCommentRequest>"
					+ "<HotelID>62574</HotelID>" + "<EffectYear>1</EffectYear>"
					+ "<RequestType>H</RequestType>"
					+ "</DomesticHotelCommentRequest>" + "</Request>");
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}

		return sb.toString();
	}

	/*
	private static String getFindPJ(String hotelCode) {
		String request = createPjRequestXml(hotelCode);
		String url = "http://openapi.ctrip.com/Hotel/D_HotelCommentList.asmx?wsdl";
		String paraName = "requestXML";
		String response = HttpAccessAdapter.SendRequestToUrl(request, url,
				paraName);
		return response;

	}*/

	
	
	public static void downloadHotelDescriptiveInfo() throws SQLException, InterruptedException {
		Connection con = null;
		java.sql.Statement st = null;
		
		List<String> hotellist=new ArrayList<String>();
		con = DBPool.getConnection();
		
		//con.
		if (con != null)
			{
			st=con.createStatement();
			ResultSet rs=st.executeQuery("SELECT distinct hotelCode FROM hotel order by hotelCode+1 ");
			  
			while(rs.next()){
				hotellist.add(rs.getString("hotelCode"));
				//
			}
		}
		st.close();
		con.close();
	   
		for(int i=0;i<hotellist.size();i++){
			System.out.println("----------------start----------");
			if(new Integer(hotellist.get(i)).intValue()>133645){
			HttpAccessAdapter.sychronizeHotelDescs(hotellist.get(i),DBPool.getConnection());
			System.out.println("----------------end-------"+hotellist.get(i)+"-----");
			
			System.out.println("");
			Thread.sleep(2000);
			}
		}
	}
	
   //ctripinterface 
	private static String createHotelRatePlanRequestXml(List<Room> roomList,String startdate,String enddate){
		StringBuilder sb = new StringBuilder();
		try {
			sb.append("<Request><Header AllianceID=\"");
			sb.append(ConfigData.AllianceId);
			sb.append("\" SID=\"");
			sb.append(ConfigData.SId);
			sb.append("\" TimeStamp=\"");
			long timestamp = SignatureUtils.GetTimeStamp();
			sb.append(timestamp);
			sb.append("\" Signature=\"");

			String signature = SignatureUtils.CalculationSignature(timestamp
					+ "", ConfigData.AllianceId, ConfigData.SecretKey,
					ConfigData.SId, ConfigData.OTA_HotelRatePlan);
			sb.append(signature);
			sb.append("\" RequestType=\"");
			sb.append(ConfigData.OTA_HotelRatePlan);
			sb.append("\" /><HotelRequest><RequestBody xmlns:ns=\"http://www.opentravel.org/OTA/2003/05\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><ns:OTA_HotelRatePlanRQ Version=\"1.0\" TimeStamp=\"");
			sb.append(DateUtil.getDateTimeForInterface("yyyy-MM-dd",new Date()));
			sb.append("\" ><ns:RatePlans>");
            for(int i=0;i<roomList.size();i++){
            	sb.append("<ns:RatePlan><ns:DateRange Start=\"");
            	sb.append(startdate);
            	sb.append("\" End=\"");
            	sb.append(enddate);
            	sb.append("\" /><ns:RatePlanCandidates><ns:RatePlanCandidate RatePlanCode=\"");
            	sb.append(roomList.get(i).getRoomTypeCode());
            	sb.append("\" AvailRatesOnlyInd=\"false\" ><ns:HotelRefs><ns:HotelRef HotelCode=\"");
            	sb.append(roomList.get(i).getHotelCode());
            	sb.append("\" /></ns:HotelRefs></ns:RatePlanCandidate></ns:RatePlanCandidates></ns:RatePlan>");
			}
            sb.append("</ns:RatePlans></ns:OTA_HotelRatePlanRQ></RequestBody></HotelRequest></Request>");
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}

		return sb.toString();
	}
	
	/*
	private static String getFindHotelRatePlan(List<Room> roomList,String startdate,String enddate) {
		String request = createHotelRatePlanRequestXml(roomList,startdate,enddate);
		String url = "http://openapi.ctrip.com/Hotel/OTA_HotelRatePlan.asmx?wsdl";
		String paraName = "requestXML";
		HttpAccessAdapter httpAccessAdapter = new HttpAccessAdapter();
		System.out.println(request);
		String response = httpAccessAdapter.SendRequestToUrl(request, url,
				paraName);
		return response;
	}*/
	
	@SuppressWarnings("unchecked")
	private static List<PricePlan> findHotelRatePlan(List<Room> roomList,String startdate,String enddate){
		
		for(int i=0;i<roomList.size();i++){
			System.out.println(roomList.get(i).getRoomTypeCode()+"-->"+roomList.get(i).getHotelCode());
		}
		List<PricePlan> pricePlanList=new ArrayList<PricePlan>();
		String response=HttpAccessAdapter.getResponseFromCtrip(ConfigData.OTA_HotelRatePlan, HttpAccessAdapter.createHotelRatePlanRequestXml(roomList, startdate, enddate));
		//System.out.println(response);
        StringReader read = new StringReader(response);
        InputSource source = new InputSource(read);
      
        SAXBuilder builder = new SAXBuilder();
        try {      
        	 Document doc = builder.build(source);  
        	 Element root = doc.getRootElement();

        	 XPath rateXPath = XPath.newInstance("//ns:Rate");
        	 rateXPath.addNamespace("ns", "http://www.opentravel.org/OTA/2003/05");
        	
			 List<Element> ratelist =(List<Element>)rateXPath.selectNodes(root);
        	// System.out.println("lala");
        	 
        	 for(int i=0;i<ratelist.size();i++){
        		 PricePlan pricePlan=new PricePlan();
        		 Element rate=ratelist.get(i);
        		 String tstamp=rate.getParentElement().getParentElement().getParentElement().getParentElement().getAttributeValue("TimeStamp");
        		// System.out.println(tstamp);
        		/* System.out.println(rate.getParentElement().getParentElement().getAttributeValue("RatePlanCode")
        				 +"---"+rate.getParentElement().getParentElement().getParentElement().getAttributeValue("HotelCode")+"-->"
        				 +rate.getAttributeValue("Start")+"-->"
        				 +tstamp.substring(0,tstamp.lastIndexOf("+")).replace("T", " ").replace(".", "[.")+"]");*/
        		 tstamp=tstamp.substring(0,tstamp.lastIndexOf(".")).replace("T", " ");
        		 System.out.println(tstamp);
        		 pricePlan.setUpdateTime(tstamp);
        		 pricePlan.setHotelCode(rate.getParentElement().getParentElement().getParentElement().getAttributeValue("HotelCode"));
        		 pricePlan.setRatePlanCode(rate.getParentElement().getParentElement().getAttributeValue("RatePlanCode"));
    			 pricePlan.setRatePlanCategory(rate.getParentElement().getParentElement().getAttributeValue("RatePlanCategory"));
    			 pricePlan.setMarketCode(rate.getParentElement().getParentElement().getAttributeValue("MarketCode"));
    			 pricePlan.setStart(rate.getAttributeValue("Start"));
    			 pricePlan.setEnd(rate.getAttributeValue("End"));
    			 pricePlan.setStatus(rate.getAttributeValue("Status"));
    			 
    			 List<Element> rateChildren =rate.getChildren();
    			 for(int j=0;j<rateChildren.size();j++){
    				 Element rateChild=rateChildren.get(j);
    				 if("BaseByGuestAmts".equals(rateChild.getName())){
    					 
    					 pricePlan.setAmountBeforeTax(((Element)(rateChild.getChildren().get(0))).getAttributeValue("AmountBeforeTax"));
    					 pricePlan.setCurrencyCode(((Element)(rateChild.getChildren().get(0))).getAttributeValue("CurrencyCode"));
    					 pricePlan.setNumberOfGuests(((Element)(rateChild.getChildren().get(0))).getAttributeValue("NumberOfGuests"));
    					
    				 }else if("GuaranteePolicies".equals(rateChild.getName())){
    					 pricePlan.setGuaranteeCode(((Element)(rateChild.getChildren().get(0))).getAttributeValue("GuaranteeCode"));
    				 }else if("CancelPolicies".equals(rateChild.getName())){
    					 Element cancelPolicies=(Element)(rateChild.getChildren().get(0));
    					 pricePlan.setCancelPenaltyStart(cancelPolicies.getAttributeValue("Start"));
    					 pricePlan.setCancelPenaltyEnd(cancelPolicies.getAttributeValue("End"));
    					 pricePlan.setCancelPenalty(((Element)(cancelPolicies.getChildren().get(0))).getAttributeValue("Amount"));//
    					 pricePlan.setListPrice(((Element)(cancelPolicies.getChildren().get(0))).getAttributeValue("ListPrice"));
    					 pricePlan.setCurrencyCode(((Element)(cancelPolicies.getChildren().get(0))).getAttributeValue("CurrencyCode"));//
    				 }else if("TPA_Extensions".equals(rateChild.getName())){
    					 Element rebatePromotion =(Element)(rateChild.getChildren().get(0));
    					 pricePlan.setRebatePromotionCode(rebatePromotion.getAttributeValue("rebatePromotionCode"));
    					 pricePlan.setRebatePromotionCurrencyAmount(rebatePromotion.getAttributeValue("Amount"));
    					 pricePlan.setRebatePromotionCurrencyCode(rebatePromotion.getAttributeValue("CurrencyCode"));
    					 pricePlan.setRebatePromotionStart(rebatePromotion.getAttributeValue("StartPeriod"));
    					 pricePlan.setRebatePromotionEnd(rebatePromotion.getAttributeValue("EndPeriod"));
    					 pricePlan.setRebatePromotionName(rebatePromotion.getAttributeValue("ProgramName"));
    					 Element desc =(Element)(rebatePromotion.getChildren().get(0));
    					 Element text =(Element)(desc.getChildren().get(0));
    					 pricePlan.setRebatePromotionDesc(text.getText());
    				 }
    				 
    			 }		 
        		pricePlanList.add(pricePlan);
        	 }
        	 
        	
        }catch (JDOMException e) {    
    		e.printStackTrace(); 
    		} catch (IOException e) {  
    			e.printStackTrace(); 
    			}
       return pricePlanList;
	}

	private static List<Room> getAllRooms() throws SQLException{
	
		
		List<Room> roomlist=new ArrayList<Room>();
		/*Room r=new Room();
		r.setHotelCode("5");
		r.setRoomTypeCode("5505");1--------1-10    2--------------11-20
		roomlist.add(r);*/
		Connection con = null;
		java.sql.Statement st = null;
		con = DBPool.getConnection();
		
		//con.
		if (con != null)
			{
			st=con.createStatement();
			ResultSet rs=st.executeQuery("SELECT h.hotelCode,h.roomTypeCode,t.hotelCityCode FROM hotel.hotelroom h " +
					"left join hotel.hotel t on  h.hotelCode=t.hotelCode");  
			while(rs.next()){
				Room r=new Room();
				r.setHotelCode(rs.getString("hotelCode"));
				r.setRoomTypeCode(rs.getString("roomTypeCode"));//
				r.setHotelCityCode(rs.getString("hotelCityCode"));
				roomlist.add(r);	
			}
		}
		st.close();
		con.close();
		return roomlist;
	}
	
	private static void jdbcPlanRooms(List roomlist,String startdate,String enddate) throws SQLException{
		Connection con = null;
		con = DBPool.getConnection();
		con.setAutoCommit(false);
		java.sql.PreparedStatement st1 = null;
		if (con != null)
		{System.out.println("connection get....................ok");}
		
		int start=0;
		int temp=0;;
		/*for(int ri=0;ri<roomlist.size();ri++){
			if((ri+1)%10==0){
				spliceroomlist=roomlist.subList(start, ri);
				start=ri+1;
				temp=0;
			} 
			else{
				temp++;
			}*/
		//489219  12543  10拼装一次报文  roomlist 
		List<PricePlan> pp=HttpAccessAdapter.findHotelRatePlan(roomlist,startdate,enddate);
		
		
	
		st1 = con.prepareStatement("insert into priceplan(ratePlanCode,hotelCode,ratePlanCategory,marketCode,minAdvancedBookingOffset," +
				"start,end,status,amountBeforeTax,currencyCode,listPrice,numberOfGuests,cancelPenalty,cancelPenaltyStart,cancelPenaltyEnd," +
				"mealsIncluded,rebatePromotionStart,rebatePromotionEnd,rebatePromotionName,rebatePromotionCode," +
				"rebatePromotionCurrencyCode,rebatePromotionCurrencyAmount,rebatePromotionDesc,guaranteeCode,updatePlanTime)"
				+ " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
		
		for (int row = 0; row < pp.size(); row++) {
		st1.setString(1, pp.get(row).getRatePlanCode());st1.setString(2, pp.get(row).getHotelCode());
		st1.setString(3, pp.get(row).getRatePlanCategory());st1.setString(4, pp.get(row).getMarketCode());
		st1.setString(5, pp.get(row).getMinAdvancedBookingOffset());st1.setString(6, pp.get(row).getStart());
		st1.setString(7, pp.get(row).getEnd());st1.setString(8, pp.get(row).getStatus());
		st1.setString(9, pp.get(row).getAmountBeforeTax());st1.setString(10, pp.get(row).getCurrencyCode());
		st1.setString(11, pp.get(row).getListPrice());st1.setString(12, pp.get(row).getNumberOfGuests());
		st1.setString(13, pp.get(row).getCancelPenalty());st1.setString(14, pp.get(row).getCancelPenaltyStart());
		st1.setString(15, pp.get(row).getCancelPenaltyEnd());st1.setString(16, pp.get(row).getMealsIncluded());
		st1.setString(17, pp.get(row).getRebatePromotionStart());st1.setString(18, pp.get(row).getRebatePromotionEnd());
		st1.setString(19, pp.get(row).getRebatePromotionName());st1.setString(20, pp.get(row).getRebatePromotionCode());
		st1.setString(21, pp.get(row).getRebatePromotionCurrencyCode());st1.setString(22, pp.get(row).getRebatePromotionCurrencyAmount());
		st1.setString(23, pp.get(row).getRebatePromotionDesc());st1.setString(24, pp.get(row).getGuaranteeCode());
		System.out.println(pp.get(row).getUpdateTime());
		st1.setTimestamp(25, Timestamp.valueOf(pp.get(row).getUpdateTime()));
		st1.addBatch();
		}
		st1.executeBatch();
		st1.clearBatch();
		
		//}
		
		con.commit();
		st1.close();
		con.close();
		
		
		Long endTime = System.currentTimeMillis();
	//	System.out.println("pst+batch：" + (endTime - beginTime) / 1000 + "秒");
		/*
		for(int i=0;i<pp.size();i++){
			System.out.println("CancelPenalty:"+pp.get(i).getAmountBeforeTax()+" CancelPenalty:"+pp.get(i).getCancelPenalty()+" CancelPenaltyEnd:"+pp.get(i).getCancelPenaltyEnd()
					+" CancelPenaltyStart:"+pp.get(i).getCancelPenaltyStart()+" CurrencyCode:"+pp.get(i).getCurrencyCode()+" End:"+pp.get(i).getEnd()
					+" GuaranteeCode:"+pp.get(i).getGuaranteeCode()+" HotelCode:"+pp.get(i).getHotelCode()+" ListPrice:"+pp.get(i).getListPrice()
					+" MarketCode:"+pp.get(i).getMarketCode()+" MealsIncluded:"+pp.get(i).getMealsIncluded()+" MinAdvancedBookingOffset:"+pp.get(i).getMinAdvancedBookingOffset()
					+" NumberOfGuests:"+pp.get(i).getNumberOfGuests()+" RatePlanCategory:"+pp.get(i).getRatePlanCategory()+" RatePlanCode:"+pp.get(i).getRatePlanCode()
					+" RebatePromotionCode:"+pp.get(i).getRebatePromotionCode()+" RebatePromotionCurrencyAmount:"+pp.get(i).getRebatePromotionCurrencyAmount()+" RebatePromotionCurrencyCode:"+pp.get(i).getRebatePromotionCurrencyCode()
					+" RebatePromotionEnd:"+pp.get(i).getRebatePromotionDesc()+" RebatePromotionEnd:"+pp.get(i).getRebatePromotionEnd()+" RebatePromotionName:"+pp.get(i).getRebatePromotionName()
					+" PromotionName:"+pp.get(i).getRebatePromotionName()+" PromotionStart:"+pp.get(i).getRebatePromotionStart()+" Start:"+pp.get(i).getStart()
					+" Status:"+pp.get(i).getStatus());
		}*/
	}
	
	private static void sychronizePlanRooms(String startdate,String enddate) throws SQLException{
		//Long beginTime = System.currentTimeMillis();
		String datestart1=DateUtil.getDateTimeForInterface("yyyy-MM-dd",new Date());
		String dateend1=DateUtil.getDateTimeForInterface("yyyy-MM-dd",DateUtil.addDaysToDate(new Date(), 3));
		/*String datestart2=DateUtil.getDateTimeForInterface("yyyy-MM-dd",DateUtil.addDaysToDate(new Date(), 29));
		String dateend2=DateUtil.getDateTimeForInterface("yyyy-MM-dd",DateUtil.addDaysToDate(new Date(), 56));
		String datestart3=DateUtil.getDateTimeForInterface("yyyy-MM-dd",DateUtil.addDaysToDate(new Date(), 57));
		String dateend3=DateUtil.getDateTimeForInterface("yyyy-MM-dd",DateUtil.addDaysToDate(new Date(), 84));
		*/
		List<Room> roomlist=HttpAccessAdapter.getAllRooms();
		int page= (roomlist.size()%ConfigData.pageSize==0)?roomlist.size()/ConfigData.pageSize:(roomlist.size()/ConfigData.pageSize+1);
        //int start=0;//int end=0+;   961    97       10
		for(int i=0;i<page;i++){
			if(i==page){
				HttpAccessAdapter.jdbcPlanRooms(roomlist.subList(ConfigData.pageSize*i, roomlist.size()),datestart1,dateend1);
				//HttpAccessAdapter.jdbcPlanRooms(roomlist.subList(ConfigData.pageSize*i, roomlist.size()),datestart2,dateend2);
				//HttpAccessAdapter.jdbcPlanRooms(roomlist.subList(ConfigData.pageSize*i, roomlist.size()),datestart3,dateend3);
			}else{
				HttpAccessAdapter.jdbcPlanRooms(roomlist.subList(ConfigData.pageSize*i, ConfigData.pageSize*(i+1)),datestart1,dateend1);
				//HttpAccessAdapter.jdbcPlanRooms(roomlist.subList(ConfigData.pageSize*i, ConfigData.pageSize*(i+1)),datestart2,dateend2);
				//HttpAccessAdapter.jdbcPlanRooms(roomlist.subList(ConfigData.pageSize*i, ConfigData.pageSize*(i+1)),datestart3,dateend3);
			}
			
		}
		
	}
	
	
	
	public static void main(String[] args) throws SQLException,
			InterruptedException, JDOMException, IOException, ParseException {
		    //HttpAccessAdapter.downloadAllHotelBasicInfo();
		    //HttpAccessAdapter.downloadHotelDescriptiveInfo();
		List<City> cities=HttpAccessAdapter.Cities();
		Connection con = null;
		con = DBPool.getConnection();
		con.setAutoCommit(false);
		java.sql.PreparedStatement st1 = null;
		if (con != null)
		{System.out.println("connection get....................ok");}
		for(int i=0;i<cities.size();i++){
			
		}
		//HttpAccessAdapter.sychronizePlanRooms("","");
		/*
		*/
		//SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	    
		/*
		java.util.Date utilDate=new Date();      
	       java.sql.Date sqlDate=new java.sql.Date(utilDate.getTime());        
	       java.sql.Time sTime=new java.sql.Time(utilDate.getTime());   
	       java.sql.Timestamp stp=new java.sql.Timestamp(utilDate.getTime());*/
	     /* System.out.println((f.parse("2013-05-16 20:28:20:22135").getYear()+1900)+"--"+(f.parse("2013-05-16 20:28:20:22135").getMonth()+1)
	    		  +"--"+f.parse("2013-05-16 20:28:20:22135").getDate()+"--"+f.parse("2013-05-16 20:28:20:22135").getHours()
	    		  +"--"+f.parse("2013-05-16 20:28:20:22135").getMinutes()+"--"+f.parse("2013-05-16 20:28:20:22135").getSeconds());
*/

	}

}
